package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ApBehaviorConstants;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Cache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.applet.AppletContext;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl  extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
            // 单页最大加载的数字
            //1.校验参数
            Integer size = dto.getSize();
            if(size == null || size == 0){
                size = 10;
            }
            size = Math.min(size,MAX_PAGE_SIZE);
            dto.setSize(size);
            //类型参数检验
            if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
                loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
            }
            //文章频道校验
            if(StringUtils.isEmpty(dto.getTag())){
                dto.setTag(ArticleConstants.DEFAULT_TAG);
            }
            //时间校验
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
            //2.查询数据
            List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
            //3.结果封装
            ResponseResult responseResult = ResponseResult.okResult(apArticles);
            return responseResult;
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(!StringUtils.isEmpty(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(type,dto);
    }

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long id = dto.getId();
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        if (id == null) {
            //新增文章,需要新增文章配置、文章内容信息
            this.save(apArticle);
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //修改文章，修改文章内容
            this.updateById(apArticle);
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(new LambdaQueryWrapper<ApArticleContent>().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

        //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());


    }

    /**
     * 加载文章时展示用户的行为
     *   { "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null || dto.getAuthorId() == null | dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean isfollow=false,islike=false,isunlike=false,iscollection=false;
        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null) {
            String userKey = user.getId().toString();
            Object  likeArticle=  cacheService.hGet(ApBehaviorConstants.LIKES_ARTICLE + dto.getArticleId(), userKey);
            if (likeArticle != null) {
                islike=true;
            }

            Object unLikeArticle = cacheService.hGet(ApBehaviorConstants.UNLIKES_ARTICLE + dto.getArticleId(), userKey);
            if (unLikeArticle != null) {
                isunlike=true;
            }

            Double follow = cacheService.zScore(ApBehaviorConstants.APUSER_FOLLOW_RELATION+userKey, dto.getAuthorId().toString());
            log.info("follow:{}",follow);
            if (follow != null) {
                isfollow=true;
            }

            Object collect = cacheService.hGet(ApBehaviorConstants.COLLECTION_BEHAVIOR + userKey, dto.getArticleId().toString());
            if (collect != null) {
                iscollection= true;
            }
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        ////{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.修改数据库信息
        ApArticle apArticle = updateArticle(mess);
        //2.计算分值
        Integer score = computeScore(apArticle);
        //3.更新redis中的频道对应文章的数据列表
        updateRedisData(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        updateRedisData(apArticle, score, ArticleConstants.DEFAULT_TAG);

    }

    private void updateRedisData(ApArticle apArticle, Integer score, String key) {
        String articleJsonArr = cacheService.get(key);
        HotArticleVo hotArticleVo = new HotArticleVo();
        BeanUtils.copyProperties(apArticle, hotArticleVo);
        hotArticleVo.setScore(score);
        //1.判断redis是否已经存在该频道对应的文章
        if (articleJsonArr == null) {
            cacheService.set(key,JSON.toJSONString( Collections.singletonList(hotArticleVo)));
            return;
        }
        boolean isExist=false;
        //存在,则判断文章是否存在
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleJsonArr, HotArticleVo.class);
        for (HotArticleVo articleVo : hotArticleVoList) {
            if (articleVo.getId().equals(apArticle.getId())) {
                //存在则替换分数，重新排名
                articleVo.setScore(score);
                isExist = true;
            }
        }
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (isExist) {
            cacheService.set(key,JSON.toJSONString(hotArticleVoList));
            return;
        }
        //不存在，判断是否大于30条数据，
        if (hotArticleVoList.size() < 30) {
            hotArticleVoList.add(hotArticleVo);
        }else {
            //大于30，则跟分数最低的那条数据比较，决定是否替换
            HotArticleVo lastArticle = hotArticleVoList.get(hotArticleVoList.size() - 1);
            if (lastArticle.getScore() < score) {
                //如果最低分的那条数据比该新的文章分数低，替换
                hotArticleVoList.remove(lastArticle);
                hotArticleVoList.add(hotArticleVo);
            }
        }
        hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        cacheService.set(key,JSON.toJSONString(hotArticleVoList));
    }

    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        Long articleId = mess.getArticleId();
        ApArticle apArticle = this.getById(articleId);
        if (apArticle != null) {
            apArticle.setComment(apArticle.getComment() == null ? 0 : apArticle.getComment() + mess.getComment());
            apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + mess.getCollect());
            apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + mess.getLike());
            apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + mess.getView());
        }
        this.updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
